package com.ruoyi.biz.imported.strategy;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.biz.imported.vo.ReqVO;
import com.ruoyi.biz.letter.domain.BizMayorHotline;
import com.ruoyi.biz.letter.domain.BizRecordLetter;
import com.ruoyi.biz.letter.mapper.BizMayorHotlineMapper;
import com.ruoyi.biz.letter.mapper.BizRecordLetterMapper;
import com.ruoyi.biz.letter.util.SysDeptUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sign.Md5Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author Fei.Cong
 * @date 2024-07-18 15:08
 */
@Slf4j
@Service
public class TelegramStrategy implements ImportedStrategy {

    @Autowired
    private BizRecordLetterMapper bizRecordLetterMapper;

    @SneakyThrows
    @Override
    public String importHandleData(ReqVO reqVO) {

        ExcelUtil<BizRecordLetter> util = new ExcelUtil<BizRecordLetter>(BizRecordLetter.class);
        List<BizRecordLetter> citySheet1List = util.importEasyExcel(reqVO.getFile().getInputStream(), 0, 1);

        if (CollectionUtil.isEmpty(citySheet1List)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int existNum = 0;
        StringBuilder msg = new StringBuilder();

        if (!reqVO.isUpdateSupport()) {
            List<BizRecordLetter> letterList = Lists.newArrayList();
            List<Long> ids = Lists.newArrayList();
            for (BizRecordLetter record : citySheet1List) {
                try {
                    String serialNumber = Md5Utils.hash(record.getLetterUsername() + record.getLetterTel() + record.getLetterTime() + record.getHandleResult());
                    BizRecordLetter entity = bizRecordLetterMapper.selectOne(new LambdaQueryWrapper<BizRecordLetter>()
                            .eq(BizRecordLetter::getSerialNumber, serialNumber)
                            .eq(BizRecordLetter::getSource, "2"));
                    if (Objects.nonNull(entity)) {
                        if (Objects.nonNull(entity.getPCategoryId()) || Objects.nonNull(entity.getSCategoryId())) {
                            failureNum++;
                            msg.append("<br/>" + failureNum + "、信访件，姓名 " + record.getLetterUsername() + " <font color='green'>已分类</font>");
                            continue;
                        } else {
                            ids.add(entity.getId());
                            existNum++;
                            msg.append("<br/>" + existNum + "、信访件，姓名 " + record.getLetterUsername() + " <font color='blue'>已更新</font>");
                        }
                    } else {
                        successNum++;
                        msg.append("<br/>" + successNum + "、信访件，姓名 " + record.getLetterUsername() + " <font color='green'>已导入</font>");
                    }
                    record.setSource("2");
                    record.setOwnerArea(SysDeptUtil.getDeptId("", record.getOwnerArea()) + "");
                    record.setPCategoryId(Optional.ofNullable(record.getFirstCategoryName()).map(Long::new).orElse(null));
                    record.setSCategoryId(Optional.ofNullable(record.getSecondCategoryName()).map(Long::new).orElse(null));
                    record.setAcceptDept(record.getDutyDept());
                    record.setSerialNumber(serialNumber);
                    letterList.add(record);
                } catch (Exception e) {
                    failureNum++;
                    String emsg = "<br/>" + failureNum + "、信访件，姓名 " + record.getLetterUsername() + " 导入失败：";
                    msg.append(emsg + e.getMessage());
                    log.error(emsg, e);
                }
            }
            if (CollectionUtil.isNotEmpty(ids)) {
                bizRecordLetterMapper.deleteByIds(ids);
            }
            bizRecordLetterMapper.insert(letterList);
        }

        msg.insert(0, "操作成功！成功 " + successNum + " 条，更新 " + existNum + " 条，失败 " + failureNum + " 条，数据如下：");

        return msg.toString();
    }
}
